const { read, write } = require('../lib/read&write')

const TOKENURL = '../data/tokens.json'

function writeToken(token) {
  const __tokens = read(TOKENURL)
  __tokens.push(token)
  write(__tokens, TOKENURL)
}

function searchToken(token) {
  const __tokens = read(TOKENURL)
  const findToken = __tokens.find((item) => item.token === token)
  return findToken
}

function removeToken(token) {
  const __tokens = read(TOKENURL)
  __tokens.splice(
    __tokens.findIndex((item) => item.token === token.token),
    1
  )
  write(__tokens, TOKENURL)
}

function editToken(token) {
  const __tokens = read(TOKENURL)
  __tokens.splice(
    __tokens.findIndex((item) => item.account === token.account),
    1,
    token
  )
  write(__tokens, TOKENURL)
}

function clearToken() {
  const time = (new Date()).getTime()
  const __tokens = read(TOKENURL)
  __tokens.filter((item) => item.time < time)
  write(__tokens, TOKENURL)
}

function searchTokenByAccount(account) {
  const __tokens = read(TOKENURL)
  const findToken = __tokens.find((item) => item.account === account)
  return findToken
}

module.exports = { writeToken, searchToken, removeToken, editToken, clearToken, searchTokenByAccount }
